from passlib.context import CryptContext
from passlib.exc import UnknownHashError
from tortoise.models import Model
from tortoise import fields

password_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


class User(Model):
    id = fields.IntField(pk=True)
    username = fields.CharField(max_length=20, description="用户名")
    realname = fields.CharField(max_length=20, description="真实名字")
    avatar = fields.CharField(max_length=255, description="头像", default="/static/system/admin/images/avatar.jpg")
    remark = fields.CharField(max_length=255, description="备注", null=True)
    password_hash = fields.CharField(max_length=128, description="哈希密码")
    enable = fields.IntField(description="启用", default=0)
    create_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    update_at = fields.DatetimeField(auto_now=True, description="创建时间")

    dept = fields.ForeignKeyField(
        "models.Dept",
        to_field="id",
        source_field="dept_id",
        null=True,
        generated=False,
    )

    # 多对多关系将在使用中通过 Tortoise 的关系定义方式建立
    roles: fields.ManyToManyRelation["Role"] = fields.ManyToManyField(
        "models.Role",
        through="admin_user_role",
        forward_key="role_id",  # 指向Role表的外键
        backward_key="user_id",  # 指向User表的外键（根据你的模型名）
    )

    class Meta:
        table = "admin_user"

    class PydanticMeta:
        exclude = ["password"]

    def set_password(self, password):
        self.password_hash = password_context.hash(password)

    # 密码加密
    @staticmethod
    def get_hash_password(password: str) -> str:
        return password_context.hash(password)

    def validate_password(self, password) -> bool:
        try:
            return password_context.verify(password, self.password_hash)
        except UnknownHashError:
            return False
